/**
 * 包装 `localStorage` 和 `sessionStorage` 以允许自动处理 key 前缀 和序列化
 */
export class StorageManager {

    private readonly prefix: string

    private readonly storage: Storage

    public constructor(prefix: string, session: Storage) {
        this.prefix = prefix
        this.storage = session
    }

    public setItem<T = Record<string, any>>(key: string, value: T): void {
        this.storage.setItem(this.key(key), JSON.stringify(value))
    }

    public getItem(key: string): any | null {
        const item = this.storage.getItem(this.key(key))
        return !!item ? JSON.parse(item) : null
    }

    public removeItem(key: string): void {
        this.storage.removeItem(this.key(key))
    }

    public clear(): void {
        this.storage.clear()
    }

    private key(key: string) {
        return this.prefix + key
    }

}
